#pragma once

#include <iostream>
#include <string>
#include <cstring>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "Common.hpp"

class InerAddr
{
public:
    InerAddr() {};
    InerAddr(struct sockaddr_in &addr) : _addr(addr)
    {
        _port = ntohs(addr.sin_port);           // 从网络中拿到的
        // _ip = inet_ntoa(addr.sin_addr); // 4字节网络风格 -> 点分十进制的字符串风格的IP
        char buffer[64];
        inet_ntop(AF_INET, &addr.sin_addr, buffer, sizeof(addr));
        _ip = buffer;
    }

    InerAddr(const std::string &ip, uint16_t port): _ip(ip), _port(port)
    {
        memset(&_addr, 0, sizeof(_addr));
        _addr.sin_family = AF_INET;
        inet_pton(AF_INET, _ip.c_str(), &_addr.sin_addr);
        _addr.sin_port = htons(_port);
    }

    InerAddr(uint16_t port): _port(port), _ip("0")
    {
        memset(&_addr, 0, sizeof(_addr));
        _addr.sin_family = AF_INET;
        _addr.sin_addr.s_addr = INADDR_ANY;
        _addr.sin_port = htons(_port);
    }

    std::string Ip() const { return _ip; }
    uint16_t Port() const { return _port; }
    const struct sockaddr_in &NetAddr() { return _addr; }
    const struct sockaddr *NetAddrPtr() { return CONV(_addr); }
    socklen_t NetAddrLen() { return sizeof(_addr); }
    bool operator==(const InerAddr& addr) const
    {
        return addr._ip == _ip && addr._port == _port;
    }
    std::string StringAddr() const
    {
        return _ip + ":" + std::to_string(_port);
    }
    ~InerAddr()
    {

    }
private:
    struct sockaddr_in _addr;
    
    std::string _ip;
    uint16_t _port;
};
